package io.renren.common.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import io.renren.common.utils.Result;
import io.renren.modules.sp.dto.SpCertificateImport;
import io.renren.modules.sp.service.SpMatchItemImportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 选手荣誉证书导入
 */
@Slf4j
public class SpStudentCerImportListener extends AnalysisEventListener<SpCertificateImport> {

    private Result result;

    private SpMatchItemImportService spMatchItemImportService;
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;
    private static int PROCESS, TOTAL = 0;
    List<SpCertificateImport> list;

    public SpStudentCerImportListener(SpMatchItemImportService userService, Result result, List<SpCertificateImport> list) {
        this.spMatchItemImportService = userService;
        this.result = result;
        this.list = list;
    }

    @Override
    public void invoke(SpCertificateImport data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        PROCESS++;
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        TOTAL = 0;
        PROCESS = 0;
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        if (!CollectionUtils.isEmpty(list)) {
            List<SpCertificateImport> saveList = new ArrayList();
            // 校验list中的Certificate字段是否重复
            List<String> certificateList = new ArrayList<>();
            for(SpCertificateImport spCertificateImport : list){
                if(StringUtils.isEmpty(spCertificateImport.getCertificate())){
                    result.setCode(0);
                    result.setData("error");
                    result.setMsg("证书编号不能为空");
                    return;
                }
                if(certificateList.contains(spCertificateImport.getCertificate())){
                    result.setCode(0);
                    result.setData("error");
                    result.setMsg(spCertificateImport.getCertificate() + "证书编号重复");
                    return;
                }
                certificateList.add(spCertificateImport.getCertificate());
            }

            for(SpCertificateImport spCertificateImport : list){
                spCertificateImport = spMatchItemImportService.checkCertificate(spCertificateImport);
                if(StringUtils.isNotEmpty(spCertificateImport.getCheckMsg())){
                    result.setCode(0);
                    result.setData("error");
                    result.setMsg(spCertificateImport.getCheckMsg());
                }
                saveList.add(spCertificateImport);
            }
            for(SpCertificateImport spCertificateImport : list){
                if(StringUtils.isNotEmpty(spCertificateImport.getCheckMsg())){
                    return;
                }
            }
            try{
                spMatchItemImportService.saveCertificateImport(saveList);
                TOTAL += saveList.size();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        log.info("存储数据库成功！");
    }
}
